import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Router } from '@angular/router';
import { storagePutOrderStateArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { PermissionService } from '../../../../service/permission.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StorageWarehousOrderService } from '../../xstorage-manage-services/storage-warehous-order.service';

@Component({
  selector: 'app-storage-warehous-list',
  templateUrl: './storage-warehous-list.component.html',
  styleUrls: ['./storage-warehous-list.component.scss']
})
export class StorageWarehousListComponent implements OnInit {
  // 路由缓存恢复时
  static updateCache: any = null;
  @ViewChild('followUpRef') followUpRef: any;

  tabVal: number = 0;
  searchOptions: any = [
    { type: 1, labelText: '入库单号', valueKey: 'warehousingNumber', value: '' },
    { type: 1, labelText: '包含商品', valueKey: 'whGood', value: '', placeholder: '编码/69码/名称' },
    { type: 1, labelText: '关联单号', valueKey: 'purchaseNumber', value: '' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'state',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...storagePutOrderStateArrs],
    },
    {
      type: 2,
      labelText: '入库类型',
      valueKey: 'types',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'content', label: 'name' },
      selectOptions: [],
    },
    {
      type: 2,
      labelText: '入库仓库',
      valueKey: 'whIds',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: [],
    },
    {
      type: 2,
      labelText: '入库品质',
      valueKey: 'quality',
      value: [],
      multiple: false,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [
        {value: 0, label: '不良品'},
        {value: 1, label: '良品'}
      ],
    },
    { type: 3, labelText: '新建时间', valueKey: ['beginTime', 'endTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '入库时间', valueKey: ['storageTime', 'endStorageTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  putTypeOptions: any[] = []; // 入库类型options
  warehouseOptions: any[] = []; // 入库仓库options

  /**
   * 审核 Modal
   * ----------------------------------------------------------------
   */
  isExamineVisible = false;
  examineLoading = false;
  examineItem: any = {};
  auditOpinion: string = '';

  /**
   * 作废 Modal
   * ----------------------------------------------------------------
   */
  isZfVisible = false;
  submitZfLoading = false;
  toVoidItem: any = {};
  toVoidRemark = ''; // 作废备注

  // 反审核
  fshLoading = false;

  /**
   * ----------------------------------------------------------------
   * check table
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  // 跟进 Modal
  initParams: any = {
    type: 3, // type 1、采购 2、SN 3、入库单 4、出库单
    relationInformation: ''
  };

  constructor(
    private msg: NzMessageService,
    private commonService: CommonService,
    private modal: NzModalService,
    private router: Router,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: StorageWarehousOrderService
  ) { }

  ngOnInit(): void {
    this.loadPutTypeOptions();
    this.loadWarehouseOptions();

    StorageWarehousListComponent.updateCache = () => {
      this.loadPutTypeOptions();
      this.loadWarehouseOptions();
      this.loadTable();
    }
  }

  /**
   * ----------------------------------------------------------------
   * table check
   * ----------------------------------------------------------------
   */
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  // 入库类型options
  async loadPutTypeOptions() {
    const res: any = await this.commonService.getDictList('inbound_type');
    this.putTypeOptions = res || [];
    this.setSearchOption(res, 'types');
  }

  // 查询仓库Options
  async loadWarehouseOptions() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data.records || [];
      this.setSearchOption(data.records, 'whIds');
    } else {
      this.msg.error(message);
    }
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getWarehousingList(params);
    this.tableParams.loading = false;

    if (code === 0) {
      this.tableParams.tableData = data.records || [];
      this.tableParams.total = data.total || 0;
    } else {
      this.msg.error(message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;

    this.setOfCheckedId.clear();
    this.loadTable();
  }

  resetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.tabVal = 0;

    this.setOfCheckedId.clear();
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 删除
  async deleteItem(item: any) {
    const {code, message}: any = await this.services.deleteWarehousingData({id: item.id});
    if (code === 0) {
      this.msg.success('删除成功');
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  // 提交审核
  async subExamineItem(item: any) {
    let params = {
      ids: [item.id],
      state: 1
    }
    const {code, data, message}: any = await this.storageCommonService.updateExamineData(params);
    if (code === 0) {
      this.msg.success(data || '操作成功');
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 审核
   * ----------------------------------------------------------------
   */
  showExamineModal(item: any) {
    this.examineItem = item;
    this.auditOpinion = '';
    this.isExamineVisible = true;
  }

  async subExamine(type: number) {
    if (type === 7 && this.commonService.isEmpty(this.auditOpinion)) {
      this.msg.warning('请输入审核意见');
      return
    }

    let params = {
      ids: [this.examineItem.id],
      state: type,
      note: this.auditOpinion
    }
    this.examineLoading = true;
    const res: any = await this.storageCommonService.updateExamineData(params);
    this.examineLoading = false;

    if (res.code === 0) {
      this.isExamineVisible = false;
      this.msg.success('操作成功');
      this.loadTable();
    } else {
      this.msg.error(res.message);
    }
  }

  // 通知入库
  noticeWarehousData() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需操作项');
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认通知仓库进行入库操作?',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ids: [...this.setOfCheckedId],
          state: 3 // 入库中
        }
        const res: any = await this.storageCommonService.updateExamineData(params);

        if (res.code === 0) {
          this.msg.success(res.data);
          this.loadTable();
        } else {
          this.msg.error(res.message);
        }
      },
      nzCancelText: '取消'
    });
  }

  // 反审核
  async deApprovalData() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需操作项');
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '该操作不可逆，而且会清空已填写数据，确认反审核?',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ids: [...this.setOfCheckedId],
          state: 8
        }
        this.fshLoading = true;
        const res: any = await this.storageCommonService.updateExamineData(params);
        this.fshLoading = false;
    
        if (res.code === 0) {
          this.msg.success(res.data);
          this.loadTable();
        } else {
          this.msg.error(res.message);
        }
      },
      nzCancelText: '取消'
    });
  }

  /**
   * ----------------------------------------------------------------
   * 作废 Modal
   * ----------------------------------------------------------------
   */
  showTovoidModal(item?: any) {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需操作项');
      return
    }

    this.toVoidRemark = '';
    this.isZfVisible = true;
  }

  async submitToVoidData() {
    if (this.commonService.isEmpty(this.toVoidRemark)) {
      this.msg.warning('请输入备注');
      return
    }

    let params = {
      ids: [...this.setOfCheckedId],
      state: 5, // 作废
      note: this.toVoidRemark
    }
    this.submitZfLoading = true;
    const {code, data, message}: any = await this.storageCommonService.updateExamineData(params);
    this.submitZfLoading = false;

    if (code === 0) {
      this.isZfVisible = false;
      this.msg.success(data);
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * other
   * ----------------------------------------------------------------
   */
  setSearchOption(array: Array<any>, val: string) {
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === val);
    this.searchOptions[temIndex].selectOptions = array || [];
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  copyText(str: any) {
    this.commonService.copyStr(str);
  }

  tabChange(val: any) {
    // 进行中: 草稿、待审核、审核通过、入库中
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'state');
    this.searchOptions[temIndex].value = val === 1 ? [0, 1, 2, 3] : [];
    this.searchParams.state = '0,1,2,3';

    this.tableParams.page = 1;
    this.loadTable();
  }

  // 跟进
  showFollowModal(item: any) {
    this.initParams.relationInformation = item.id;
    this.followUpRef.isModelVisible = true;
  }

  // 编辑跳转
  jumpEditPage(item: any) {
    let url: string = item.type === 1 ? '/storage-center/storage-warehous-editcg' : '/storage-center/storage-warehous-editpt';
    let params: any = {
      id: item.id,
      type: 1
    }

    if (item.type === 1) {
      params.purchaseNumber = item.purchaseNumber;
    }
    
    this.router.navigate([url], {
      queryParams: {
        ...params
      }
    })
  }
}
